/**
 *bpmnjs的工具类
 */
// import ExtensionElementsHelper from 'bpmn-js-properties-panel/lib/helper/ExtensionElementsHelper';
import ElementCompantMap from '../const/ElementCompantMap';
import elementHelper from "@/views/flow/act/edit-modeler/js/helper/ElementHelper";
// import {deleteByRuleNumberApi, createApi} from '@/views/coding/city/ctcEventRule/api.js'
const getBusinessObject = require('bpmn-js/lib/util/ModelUtil').getBusinessObject;


export default {
    getBpmnTempate () {
        return '<?xml version="1.0" encoding="UTF-8"?>' +
        '<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd" id="sample-diagram" targetNamespace="http://activiti.org/bpmn">' +
        '<bpmn2:process id="process_waiting_for_replace_id" name="process_waiting_for_replace_name" isExecutable="true">' +
        '</bpmn2:process>' +
        '<bpmndi:BPMNDiagram id="BPMNDiagram_1">' +
        '<bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">' +
        '</bpmndi:BPMNPlane>' +
        '</bpmndi:BPMNDiagram>' +
        '</bpmn2:definitions>';
    },
    //设置元素
    setElement (element, vm) {
        if (element === undefined) {
            element = vm.bpmnModeler.get('canvas').getRootElement();
        }
        vm.propsComponent = this.getComponentByEleType(element.type);
        vm.element = element;
    },
    /*getRuleNumberString(element) {
      let ruleNumberString = ''
      if (element && element.businessObject && element.businessObject.extensionElements && element.businessObject.extensionElements.values) {
        element.businessObject.extensionElements.values.forEach(listener => {
          if (listener.delegateExpression === '${assigneeListener}') {
            listener.fields.forEach(field => {
              if (field.name === 'ruleNumber') {
                ruleNumberString = field.string
              }
            })
          }
        })
      }
      return ruleNumberString
    },*/
    async removedElement(element, bpmnFactory) {
      if (element.type === 'bpmn:UserTask'){
        let eventRuleNumber = this.getRuleNumberString(element)
        console.log('delete eventRuleNumber:'+eventRuleNumber)
        if (eventRuleNumber=='' || eventRuleNumber===undefined) {
          return ;
        }
        //deleteByRuleNumberApi({'eventRuleNumber':eventRuleNumber})
      }
    },
    // 页面添加节点时，加入的属性
    async appendDefaultInfoToElement(element, bpmnFactory) {
      console.log('=============>element appendDefaultInfoToElement')
      if (element.type === 'bpmn:UserTask'){
        /*
        // 数据库创建一个node
        let eventRuleNumber = this.getRuleNumberString(element)
        if (eventRuleNumber!=='') {
          return ;
        }
        const data =
          {
            "ctcEventTypeId":0,
            "ctcEventGradeId":0,
            "ctcAssignIsauto":1,
            "ctcAssignManType":0,
            "cmpyConditionRadio":1,
            "userConditionRadio":1,
            "cmpyConditionCount":1,
            "userConditionCount":1,
            "name":"AutoAddNodeFromSimpleDesign"
          }
        const result = {}//await createApi(data)
        if (!result.success) {
          console.log("创建失败")
          return ;
        }
        eventRuleNumber = result.obj.eventRuleNumber
        console.log("service create node success, "+eventRuleNumber)
        */
        //const varPre = eventRuleNumber+"_";
        const varPre = "";
        //
        element.businessObject.assignee="${user.userId}"

        let extensionElements = element.businessObject.get('extensionElements');
        if(!extensionElements) {
          extensionElements = elementHelper.createElement('bpmn:ExtensionElements', null, element, bpmnFactory);
        }
        let length = extensionElements.get('values').length;
        for (let i = 0; i < length; i++) {
          // 清除旧值
          extensionElements.get('values').pop();
        }
        length = extensionElements.get('values').length;

        // event start
        let executionListener = elementHelper.createElement('activiti:ExecutionListener', null, element, bpmnFactory);
        executionListener.event = 'start';
        executionListener.delegateExpression = '${assigneeListener}';
        /*//ruleNumber
        let field = elementHelper.createElement('activiti:Field', null, element, bpmnFactory);
        field.name='ruleNumber'
        field.string=eventRuleNumber
        executionListener.get('fields').push(field)
        //varPre
        field = elementHelper.createElement('activiti:Field', null, element, bpmnFactory);
        field.name='varPre'
        field.string=varPre
        executionListener.get('fields').push(field)*/
        //fork:    {'name':'fork', list:[{'name':'完成任务','val':1},'name':'转城管','val':0}]}
        let field = elementHelper.createElement('activiti:Field', null, element, bpmnFactory);
        field.name='fork'
        field.string='' // {"name":"fork", "list":[{"name":"完成任务","val":1},{"name":"转城管","val":0}]}
        executionListener.get('fields').push(field)
        //
        extensionElements.get('values').push(executionListener)
        // event end

        executionListener = elementHelper.createElement('activiti:ExecutionListener', null, element, bpmnFactory);
        executionListener.event = 'end';
        executionListener.delegateExpression = '${taskCompleteListener}';
        field = elementHelper.createElement('activiti:Field', null, element, bpmnFactory);
        field.name='clearVars'
        field.string='true'
        executionListener.get('fields').push(field)
        field = elementHelper.createElement('activiti:Field', null, element, bpmnFactory);
        field.name='varPre'
        field.string=varPre
        executionListener.get('fields').push(field)
        extensionElements.get('values').push(executionListener)

        // task assignment
        executionListener = elementHelper.createElement('activiti:TaskListener', null, element, bpmnFactory);
        executionListener.event = 'assignment';
        executionListener.delegateExpression = '${bindAnswerWfTaskListener}';
        extensionElements.get('values').push(executionListener)
        // set to element
        element.businessObject.set('extensionElements',extensionElements)

        let loopCharacteristics = elementHelper.createElement('bpmn:MultiInstanceLoopCharacteristics', null, element, bpmnFactory);
        loopCharacteristics.isSequential = false;
        loopCharacteristics.collection = varPre+'userList';
        loopCharacteristics.elementVariable = 'user';
        let completionCondition = elementHelper.createElement('bpmn:Expression', null, element, bpmnFactory);
        completionCondition.body = '${instanceCompleteTaskListener.execUserInstance(execution)}'
        loopCharacteristics.completionCondition = completionCondition
        element.businessObject.set('loopCharacteristics',loopCharacteristics)
      }
      if (element.type === 'bpmn:EndEvent'){
        let extensionElements = element.businessObject.get('extensionElements');
        if(!extensionElements) {
          extensionElements = elementHelper.createElement('bpmn:ExtensionElements', null, element, bpmnFactory);
        }
        let length = extensionElements.get('values').length;
        console.log("length:"+length)
        for (let i = 0; i < length; i++) {
          // 清除旧值
          extensionElements.get('values').pop();
        }
        length = extensionElements.get('values').length;
        console.log("length pop:"+length)

        // event end
        let executionListener = elementHelper.createElement('activiti:ExecutionListener', null, element, bpmnFactory);
        executionListener.event = 'end';
        executionListener.delegateExpression = '${mainTaskCompleteListener}';
        extensionElements.get('values').push(executionListener)

        // set to element
        element.businessObject.set('extensionElements',extensionElements)
      }
      if (element.type === 'bpmn:StartEvent'){
        let extensionElements = element.businessObject.get('extensionElements');
        if(!extensionElements) {
          extensionElements = elementHelper.createElement('bpmn:ExtensionElements', null, element, bpmnFactory);
        }
        let length = extensionElements.get('values').length;
        console.log("length:"+length)
        for (let i = 0; i < length; i++) {
          // 清除旧值
          extensionElements.get('values').pop();
        }
        length = extensionElements.get('values').length;
        console.log("length pop:"+length)

        // set to element
        element.businessObject.set('extensionElements',extensionElements)
      }
    },
    listenerValue(element, newVal, bpmnFactory){
      if(newVal) {
        let extensionElements = element.businessObject.get('extensionElements');
        if(!extensionElements) {
          extensionElements = elementHelper.createElement('bpmn:ExtensionElements', null, element, bpmnFactory);
        }
        const length = extensionElements.get('values').length;
        for (let i = 0; i < length; i++) {
          // 清除旧值
          extensionElements.get('values').pop();
        }
        this.eventType.forEach(evt => {
          const executionListener = elementHelper.createElement('activiti:ExecutionListener', null, element, bpmnFactory);
          executionListener.$attrs['event'] = evt;
          executionListener.$attrs[this.listenerType] = newVal;
          extensionElements.get('values').push(executionListener)
        });
        const modeling = bpmnModeler.get('modeling');
        modeling.updateProperties(this.element, {
          extensionElements: extensionElements
        })
      }
    },
    isImplicitRoot (element) {
        return element.id === '__implicitroot';
    },
    //更新模型属性
    updateProperties(element,properties){
        let bo = getBusinessObject(element);
        Object.keys(properties).forEach(key => {
            bo.set(key,properties[key]);
        });
    },
    //通过命令更新属性
    updatePropertiesByCmd(element,commandStack,properties){
        commandStack.execute('element.updateProperties',{ element: element, properties: properties });
    },
    //获取元素的属性
    getProperties(element,propNames){
        let bo = this.getBo(element);
        let properties = {};
        for(let propName of propNames ){
            properties[propName] = bo.get(propName);
        }
        return properties;
    },
    //获取单个元素属性
    getPropertie(element,propName){
        let bo = this.getBo(element);
        return bo.get(propName);
    },

    //获取元素的模型对象
    getBo(element){
        return getBusinessObject(element);
    },
    //通过元素类型获取相应的组件
    getComponentByEleType(type){
        return  ElementCompantMap[type];
    },
    //创建一个元素
    createElement(vm,elementName, properties){
        let bpmnFactory = vm.bpmn.bpmnFactory;
        return bpmnFactory.create(elementName, properties);
    }
};
